"""
用户相关数据模型
"""

from tortoise import fields
from .base import BaseModel


class User(BaseModel):
    """
    用户模型
    """
    username = fields.CharField(max_length=50, unique=True, description="用户名")
    email = fields.CharField(max_length=100, unique=True, null=True, description="邮箱")
    hashed_password = fields.CharField(max_length=255, description="加密后的密码")
    full_name = fields.CharField(max_length=100, null=True, description="真实姓名")
    is_active = fields.BooleanField(default=True, description="是否激活")
    is_superuser = fields.BooleanField(default=False, description="是否为超级用户")
    last_login = fields.DatetimeField(null=True, description="最后登录时间")
    
    class Meta:
        table = "users"
        table_description = "用户表"
        
    def __str__(self):
        return f"User(id={self.id}, username={self.username})"
    
    async def update_last_login(self):
        """更新最后登录时间"""
        from datetime import datetime
        self.last_login = datetime.now()
        await self.save()


class UserProfile(BaseModel):
    """
    用户资料扩展模型
    """
    user = fields.OneToOneField('models.User', related_name='profile', description="关联用户")
    avatar = fields.CharField(max_length=255, null=True, description="头像URL")
    phone = fields.CharField(max_length=20, null=True, description="手机号")
    birthday = fields.DateField(null=True, description="生日")
    gender = fields.CharField(max_length=10, null=True, description="性别")
    bio = fields.TextField(null=True, description="个人简介")
    
    class Meta:
        table = "user_profiles"
        table_description = "用户资料表"
        
    def __str__(self):
        return f"UserProfile(user_id={self.user_id})"


class UserLoginLog(BaseModel):
    """
    用户登录日志模型
    """
    user = fields.ForeignKeyField('models.User', related_name='login_logs', description="关联用户")
    login_time = fields.DatetimeField(auto_now_add=True, description="登录时间")
    ip_address = fields.CharField(max_length=45, null=True, description="登录IP地址")
    user_agent = fields.TextField(null=True, description="用户代理")
    login_success = fields.BooleanField(default=True, description="登录是否成功")
    failure_reason = fields.CharField(max_length=255, null=True, description="失败原因")
    
    class Meta:
        table = "user_login_logs"
        table_description = "用户登录日志表"
        
    def __str__(self):
        return f"UserLoginLog(user_id={self.user_id}, time={self.login_time})"